Skip to content

Add shell completion generation - #764

Merged
kevincodex1 merged 3 commits into
mainfrom
feat/499-shell-completion
Jul 22, 2026
Merged

kevincodex1 merged 3 commits into
mainfrom
feat/499-shell-completion

Conversation

@anandh8x

@anandh8x anandh8x commented Jul 20, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • add zero completions <shell> for Bash, Zsh, Fish, PowerShell, and Elvish
  • cover top-level aliases, nested subcommands, root flags, and common exec flags from one shared command tree
  • add completion help, safe installation examples, and usage errors for missing or unsupported shells

Verification

  • make fmt-check
  • go vet ./...
  • go test ./...
  • go run ./cmd/zero-release build
  • go run ./cmd/zero-release smoke
  • pinned advisory lint against the PR diff
  • go run golang.org/x/vuln/cmd/govulncheck@v1.3.0 ./...
  • git diff HEAD --check

Closes #499

Summary by CodeRabbit

  • New Features

    • Added a completions command to generate shell completion scripts.
    • Supports Bash, Zsh, Fish, PowerShell, and Elvish.
    • Updated CLI help to list completions and improved completion coverage for nested commands/aliases and common options.
  • Tests

    • Added/expanded tests for completions help output, shell argument validation, and generation for every supported shell.
    • Added shell-specific structural checks (e.g., balanced blocks) and optional on-host script syntax validation when the shell is installed.

Add zero completions for bash, zsh, fish, PowerShell, and Elvish using one shared command tree that covers aliases, nested commands, root flags, and common exec flags.

Validate missing and unsupported shell arguments as usage errors and document safe installation examples in command help.

Refs #499
@coderabbitai

coderabbitai Bot commented Jul 20, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 31f5584a-69fa-4287-bcdc-3e93bce7fb4e

📥 Commits

Reviewing files that changed from the base of the PR and between 7ce144a and c0a1cbe.

📒 Files selected for processing (2)
  • internal/cli/completions.go
  • internal/cli/completions_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/cli/completions_test.go
  • internal/cli/completions.go

Walkthrough

Adds zero completions <shell> for bash, zsh, fish, PowerShell, and Elvish. The CLI builds completion contexts from a static command tree, emits shell-specific scripts, integrates help output, validates arguments, and tests command coverage.

Changes

Shell completions

Layer / File(s) Summary
Completion tree and context generation
internal/cli/completions.go
Defines the command and flag tree, derives deterministic completion contexts and transitions, and formats shell candidates.
Command dispatch and shell writers
internal/cli/app.go, internal/cli/completions.go
Registers completions, validates shell arguments, prints help, and generates scripts for five shells.
CLI and generator validation
internal/cli/completions_test.go
Tests help output, argument rejection, shell generation, script structure and syntax, aliases, nested commands, and common flags.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant runCompletions
  participant completionContexts
  participant ShellWriter
  participant stdout
  CLI->>runCompletions: dispatch completions <shell>
  runCompletions->>completionContexts: derive command contexts
  runCompletions->>ShellWriter: generate selected shell script
  ShellWriter->>stdout: write completion script
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: adding shell completion generation.
Linked Issues check ✅ Passed The PR implements zero completions for the requested shells from a shared CLI tree and adds help and tests matching the issue goals.
Out of Scope Changes check ✅ Passed The changes stay focused on the completions command, help text, and tests with no clear unrelated additions.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/499-shell-completion

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/cli/completions.go`:
- Around line 145-164: Update writeCompletionsHelp to include an Elvish
installation example alongside the existing shell completion examples, using the
supported elvish target and an appropriate output or sourcing form.
- Line 35: Update the completions command node in completionContexts to include
child names for every static shell supported by runCompletions, matching the
cases in its switch. Keep the existing completions names and help flags
unchanged, and exclude only the dynamic completion sources.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 539d73c4-d9eb-4545-8bbc-04ef03d6bc00

📥 Commits

Reviewing files that changed from the base of the PR and between 974fc03 and 056373f.

📒 Files selected for processing (3)
  • internal/cli/app.go
  • internal/cli/completions.go
  • internal/cli/completions_test.go

Comment thread internal/cli/completions.go Resolved
Comment thread internal/cli/completions.go Resolved
@github-actions

github-actions Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Zero automated PR review

Verdict: No blockers found

Blockers

  • None found.

Validation

  • [pass] Diff hygiene: git diff --check
  • [pass] Tests: go test ./...
  • [pass] Build: go run ./cmd/zero-release build
  • [pass] Smoke build: go run ./cmd/zero-release smoke

Scope

Head: c0a1cbee877d
Changed files (3): internal/cli/app.go, internal/cli/completions.go, internal/cli/completions_test.go

This deterministic review checks validation status and basic diff hygiene. A human reviewer still owns product judgment and design quality.

Expose every supported shell as a completions subcommand candidate and document Elvish activation.

Refs #499
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jul 20, 2026

@gnanam1990 gnanam1990 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

REQUEST CHANGES — the elvish script is syntactically invalid and cannot be sourced, and the test suite can't detect that. Everything else is in good shape; bash and zsh are genuinely solid.

Up front on method, because it matters for how much weight to give each part: I executed bash and zsh (both installed here) — syntax checks and real functional completion. fish, powershell and elvish are not installed, so those I reviewed by reading the generated output. The elvish finding below does not depend on running elvish: it's an objective brace count.


[Blocker] The elvish script is unparseable — every if/elif block is opened and never closed

writeElvishCompletions (internal/cli/completions.go:376-384, and again at :388-396) emits an opening { per branch but only writes one closing } after the whole loop:

fmt.Fprintf(w, "        %s (== $context'|'$token %q) {\n            set context = %q\n", keyword, key, transitions[key])

Generated output:

        if (== $context'|'$token "auth|chatgpt") {
            set context = "auth chatgpt"
        elif (== $context'|'$token "auth|login") {
            set context = "auth login"
        elif ...

Counting the emitted file: 379 { against 4 }. The transition loop alone opens 1 if + 187 elif blocks and closes exactly one. The candidates section at the bottom has the identical defect:

    elif (== $context "worktrees") {
        put prepare
    elif (== $context "worktrees prepare") {
        put 
    }
}

Elvish requires each block closed before the next keyword — if $cond { body } elif $cond2 { body2 }. As emitted, this cannot parse, so zero completions elvish produces a file that fails on source. For comparison, the other four are all balanced: bash 3/3, zsh 3/3, powershell 384/384, and fish correctly uses one switch … 188 case … one end.

There is a second, independent bug in the same function. Elvish's == is numeric equality (eq is the general value comparison; older releases used ==s for strings). (== $context'|'$token "auth|chatgpt") compares strings with a numeric operator, so even with balanced braces every comparison would fail at runtime.

Fix: close each branch and switch the operator — } elif (eq $context'|'$token "…") { — with a final } after the chain. Same in both loops.

For what it's worth, $args[1..-1] is correct and I'd leave it alone: Elvish ranges are upper-exclusive, so this deliberately drops the word currently being completed, which is what a completer wants.

[Major] The tests cannot detect a malformed script — which is why the above shipped green

TestCompletionsGeneratesEverySupportedShell (internal/cli/completions_test.go:63-91) asserts only three things per shell: exit success, one marker substring, and the four substrings daemon / mcp oauth / sandbox grants / --output-format. The broken elvish output contains all five — I checked each individually — so go test ./internal/cli/ -run TestCompletion passes clean against a file that no elvish can parse.

That's the gap worth closing regardless of the blocker: the suite validates content and never shape, so any future structural regression in any of the five emitters lands silently.

Fix, cheapest first:

  1. Assert structural balance per shell in the existing table — brace balance for elvish/powershell, switch/end for fish. That alone catches this class.
  2. Better, for the two shells CI already has: shell out to bash -n and zsh -n on the generated script, skipping via exec.LookPath when absent. I ran both here and they pass, so this is a cheap, non-flaky guard.

Minor

Agreed with CodeRabbit's two, and I confirmed the first empirically rather than by reading — sourcing the generated bash script and driving the completion function gives:

[zero completions  | cword=2]  ->  -h --help

so the completion generator can't complete its own shell argument. The five shell names are a static list already present in the switch at :125-138; adding children: leafNodes("bash","zsh","fish","powershell","elvish") to the completions node at :35 fixes it.

Nit

Nothing fails when a new CLI command is added without updating completionRoot. The tree is accurate today (see below), but it's hand-maintained with no guard, so it will drift silently. A test comparing the root node's names against the command list in app.go would pin it.


What's genuinely good here

I want to be concrete about this rather than polite, because the parts that work are the parts that were hard:

  • bash is correct, not just syntactically valid. bash -n passes, and driving _zero directly with COMP_WORDS/COMP_CWORD returns the right candidates at every position I tried — top level, a partial prefix (zero ex → exec), a nested subcommand (zero sessions → list children lineage tree rewind-plan rewind compact-plan), and flags after a subcommand (zero exec -- → the full flag set). zsh passes zsh -n.
  • The command tree is accurate and complete. Every one of the 33 commands in zero --help is completed — no gaps. It also completes 13 undocumented aliases (backend, change, init, plugin, repoinfo, repomap, session, skill, specialists, tool, trust, upgrade, worktree), and I ran each one against the built binary to confirm they're all real, working aliases rather than phantom entries. That's better than most hand-maintained completion trees manage.
  • One shared tree feeding five emitters is the right structure, and completionContexts handling alias expansion into multiple paths is a nice touch — it's why zero session <TAB> and zero sessions <TAB> both work.
  • Everything interpolated into the scripts is a compile-time constant from completionRoot — nothing from argv, env, or the filesystem — so there's no injection surface here at all. I looked specifically because sourced shell scripts are a natural place for it.

Verification

gofmt clean on all three files, go vet ./internal/cli/ clean, go test ./internal/cli/ -run TestCompletion passes (which is precisely the problem — see the Major). All five shells generate non-empty output with exit 0. No pre-existing failures were implicated; I didn't need a base comparison since nothing failed.

Merge is kevin's call per the program gate.

Close generated Elvish conditional branches, use value equality, and validate generated script structure plus native Bash and Zsh syntax.

Refs #499

@gnanam1990 gnanam1990 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

APPROVE. Re-reviewed at c0a1cbe. The blocker is fixed on both counts, the test gap is closed better than I suggested, and both minors are done.

I went further than reading the diff this round: I installed elvish 0.21.0 and ran the real interpreter against both versions of the script, so the central claim is now verified rather than inferred.

Blocker — fixed, and confirmed with real elvish

Both halves are addressed:

  • Brace structure. The generator now emits } elif (…) {, and the file balances at 389 { / 389 } (was 379/4).
  • Operator. (== …) → (eq …): zero occurrences of (== remain, 387 of (eq . This was the half that would still have failed at runtime even with balanced braces, so I'm glad it was caught too.

Verified by execution, not inspection:

OLD (056373f):  elvish -compileonly  ->  Multiple parse errors: should be '}'
NEW (c0a1cbe):  elvish -compileonly  ->  parses and compiles cleanly

One note so the output isn't misread if you try this yourself: running elvish -compileonly on the script as-shipped reports cannot find variable $edit:completion:arg-completer. That is not a defect — edit: is the interactive editor module and isn't bound in non-interactive mode. Stubbing line 2 to a plain var isolates syntax from module availability, and with that done the new script compiles clean while the old one still fails on parse errors. So the fix is genuinely correct, not merely balanced.

If you ever want elvish in CI, elvish -compileonly is the equivalent of bash -n and would slot straight into assertNativeShellSyntax — though pulling in an elvish binary is a heavier lift than the two shells already covered, so I wouldn't push for it.

Major — fixed, and mutation-tested

Both suggestions landed, plus one I didn't think of:

  • assertBalancedBraces for powershell/elvish (completions_test.go:93)
  • assertNativeShellSyntax shelling out to bash -n / zsh -n, gated on exec.LookPath with t.Skipf when the shell is absent (:135) — including the skip detail, so this won't turn into a flaky Windows failure
  • assertBalancedFishBlocks (:101), a proper depth counter over function/for/switch/if vs end, which is more precise than the brace count I proposed and correctly models fish's grammar

The important question is whether the new guard would actually have caught the original bug, so I mutation-tested it — restored the old generator, kept the new tests:

--- FAIL: TestCompletionsGeneratesEverySupportedShell/elvish
    completions_test.go:97: unbalanced braces: 379 opening, 4 closing

It fires, with the exact numbers from my review. That's a real regression test, not a decorative one.

Minors — both fixed

  • zero completions <TAB> now completes the shell list. Verified functionally by sourcing the generated bash script and driving _zero: [zero completions |cw=2] -> -h --help bash zsh fish powershell elvish. TestCompletionTreeCoversAliasesNestingAndCommonFlags now pins it too.
  • The elvish install example is in the help (eval (zero completions elvish | slurp)) and asserted in TestCompletionsHelpAndRootHelp.

One nit, non-blocking

assertBalancedBraces counts braces anywhere in the text, including inside quoted strings. That's sound today because every command name, alias and flag in completionRoot is brace-free, so the count can't be skewed. But it would silently mis-handle a future command containing { or }. Not worth changing now — the fish checker's line-oriented approach is the model if it ever matters.

Verification

Re-ran everything on a clean tree at c0a1cbe:

  • All five shells generate non-empty output, exit 0; all five balance.
  • bash -n and zsh -n pass. bash is still functionally correct — spot-checked top level, nested (zero sessions → the seven subcommands), and prefix filtering (zero exec --mod → --mode --model).
  • gofmt and go vet ./internal/cli/ clean.
  • go test ./internal/cli/ -run TestCompletion — all four tests pass, including the five new per-shell subtests.

Good turnaround, and the elvish fix addressed the operator bug rather than just silencing the brace count — which is the difference between it parsing and it working.

Merge is kevin's call per the program gate.

@anandh8x
anandh8x requested a review from Vasanthdev2004 July 20, 2026 06:59
@kevincodex1
kevincodex1 merged commit ab2f9fb into main Jul 22, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add shell completions command (zero completions <shell>)

3 participants